<template>
  <div>
    <!-- 功能条 -->
    <el-row class="buttonRow">
      <el-col :span="2">
        <el-button type="primary" size="mini" @click="openCreateFormDialog">创建柜组</el-button>
      </el-col>
      <el-col :span="22">
        <el-input v-model="getReq.keyword" size="mini" placeholder="请输入关键词..." clearable @keyup.enter.native="search" @clear="clearKeyword">
          <el-button slot="append" icon="el-icon-search" @click="search" />
        </el-input>
      </el-col>
    </el-row>
    <!-- 列表 -->
    <el-row class="tableRow">
      <div class="tableDiv">
        <el-table :data="tableAry" border stripe @expand-change="expandTable">
          <el-table-column label="序号" prop="index" width="50px" :show-overflow-tooltip="true" />
          <el-table-column label="详情" width="50px" type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="table-expand">
                <el-form-item label="拥有的智能柜">
                  <span>{{ props.row.hasChests }}</span>
                </el-form-item>
                <el-form-item label="具备其使用权的用户">
                  <span>{{ props.row.hasUsers }}</span>
                </el-form-item>
                <el-form-item label="Id">
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="创建时间">
                  <span>{{ props.row.gmtCreate }}</span>
                </el-form-item>
                <el-form-item label="更新时间">
                  <span>{{ props.row.gmtModified }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="组名" prop="chestGroupName" width="200px" :show-overflow-tooltip="true" />
          <el-table-column label="说明" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="操作" width="360px">
            <template slot-scope="scope">
              <template>
                <el-button type="primary" size="mini" @click="setChests(scope.row)">分配智能柜</el-button>
              </template>
              <template>
                <el-button type="primary" size="mini" @click="setUsers(scope.row)">分配用户</el-button>
              </template>
              <template>
                <el-button type="warning" size="mini" @click="openEditFormDiglog(scope.row)">编辑</el-button>
              </template>
              <template>
                <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <!-- 页条 -->
    <el-row type="flex" justify="center" class="pageRow">
      <el-pagination
        :current-page="getReq.currentPage"
        :page-sizes="[10, 25, 50]"
        :page-size="getReq.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 表单对话框 -->
    <el-dialog :visible.sync="formDialogVisible" width="50%" top="5vh" :close-on-click-modal="false" :show-close="false">
      <el-row class="formTitleRow">
        <div class="formTitle">{{ formTitle }}</div>
      </el-row>
      <el-divider />
      <el-row class="formRow">
        <el-form ref="form" :rules="rules" :model="form" label-width="120px">
          <el-form-item label="机柜组名" prop="chestGroupName">
            <el-input ref="input" v-model="form.chestGroupName" />
          </el-form-item>
          <el-form-item label="说明" prop="remark">
            <el-input v-model="form.remark" type="textarea" :autosize="{ minRows:4, maxRows: 8}" />
          </el-form-item>
        </el-form>
      </el-row>
      <el-divider />
      <el-row>
        <div class="formButtonDiv">
          <el-button size="mini" class="formButton" @click="closeFormDialog">取 消</el-button>
          <el-button type="primary" size="mini" class="formButton" @click="submit">提 交</el-button>
        </div>
      </el-row>
    </el-dialog>
    <!-- 配置对话框 -->
    <el-dialog :visible.sync="configDialogVisible" width="50%" top="5vh" :close-on-click-modal="false" @close="closeConfigDialog">
      <ConfigPage
        v-if="configDialogVisible"
        :in-config-target="configTarget"
        :in-config-ary="configAry"
        @submitConfig="submitConfig"
        @closeConfigPage="closeConfigDialog"
      />
      <!-- v-if="configDialogVisible" 做到创建销毁组件，可以在组件中使用生命周期钩子 -->
    </el-dialog>
  </div>
</template>

<script>
import ConfigPage from '@/components/fsd/ConfigPage'
import { createChestGroupAPI, getChestGroupsAPI, editChestGroupAPI } from '@/util/back_front_api/chestGroups.js'
import { getChestsAndStationsAllAPI } from '@/util/back_front_api/chests.js'
import { getChestsAndStationsByChestGroupAPI, changeChestsByChestGroupAPI } from '@/util/back_front_api/chests_chestGroups.js'
import { changeUsersByChestGroupAPI, getUsersByChestGroupAPI } from '@/util/back_front_api/users_chestGroups.js'
import { getUsersAllAPI } from '@/util/back_front_api/users.js'


export default {
  name: 'fsdchestgroup',
  components: {
    ConfigPage
  },
  data() {
    return {
      // 列表
      tableAry: [],
      // 页条
      total: 0,
      // 表单对话框
      formTitle: '',
      formDialogVisible: false,
      form: {
        chestGroupName: '',
        remark: ''
      },
      rules: {
        chestGroupName: [
          { required: true, message: '请输入柜组名', trigger: 'blur' }
        ]
      },
      // 配置对话框
      configDialogVisible: false,
      configTarget: {
        id: '',
        dialogTitle: '',
        itemTitle: '',
        name: '',
        type: ''
      },
      configAry: [],
      // 请求
      getReq: {
        keyword: '',
        currentPage: 1,
        pageSize: 10
      },
      createReq: {
        chestGroupName: '',
        remark: ''
      },
      editReq: {
        id: '',
        chestGroupName: '',
        remark: ''
      },
      getByChestGroupReq: {
        id: ''
      },
      changeReq: {
        id: '',
        idAry: []
      }
    }
  },
  created() { // 使用keepalive后不能刷新的情况，在activated中获取list
    this.getChestGroups()
  },
  methods: {
    // 功能条
    clearKeyword() {
      this.getReq.keyword = ''
      this.getChestGroups()
    },
    search() {
      this.getReq.currentPage = 1
      this.getChestGroups()
    },
    // 页条
    handleSizeChange(size) {
      this.getReq.pageSize = size
      this.getChestGroups()
    },
    handleCurrentChange(page) {
      this.getReq.currentPage = page
      this.getChestGroups()
    },
    // 表单对话框
    openCreateFormDialog() {
      this.formDialogVisible = true

      this.$nextTick(() => {
        this.$refs.input.focus()
        this.$refs.form.resetFields()

        this.formTitle = '创建柜组'
      })
    },
    openEditFormDiglog(row) {
      this.editReq.id = ''
      this.editReq.chestGroupName = ''
      this.editReq.remark = ''

      this.formDialogVisible = true

      this.$nextTick(() => {
        this.$refs.input.focus()
        this.$refs.form.resetFields()

        this.formTitle = '编辑柜组'

        this.form.chestGroupName = row.chestGroupName
        this.form.remark = row.remark

        this.editReq.id = row.id
      })
    },
    closeFormDialog() {
      this.formTitle = ''
      this.formDialogVisible = false
    },
    create() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('将会创建你所设置的柜组, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.createReq.chestGroupName = this.form.chestGroupName
            this.createReq.remark = this.form.remark
            createChestGroupAPI(this.createReq).then(res => {
              this.utilMessage.success(res.msg)
              setTimeout(() => {
                this.getChestGroups()
              }, 500)
            }).catch(err => {
              console.log(err)
            })
            this.closeFormDialog()
          }).catch(() => {
            return false
          })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    edit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('将会修改你所选的柜组的信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.editReq.chestGroupName = this.form.chestGroupName
            this.editReq.remark = this.form.remark
            editChestGroupAPI(this.editReq).then(res => {
              this.utilMessage.success(res.msg)
              console.log(res)
              setTimeout(() => {
                this.getChestGroups()
              }, 500)
            }).catch(err => {
              console.log(err)
            })
            this.closeFormDialog()
          }).catch(() => {
            return false
          })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    submit() {
      if (this.formTitle === '创建柜组') {
        this.create()
      } else if (this.formTitle === '编辑柜组') {
        this.edit()
      } else {
        this.utilMessage.warning('formTitle有误。')
      }
    },
    // 配置对话框
    async setChests(row) {
      let checkItemTemp = []
      let noSameStation = true
      this.configAry = []
      this.configTarget.dialogTitle = '分配该智能柜组所拥有的智能柜'
      this.configTarget.itemTitle = '请选择智能柜：'
      this.configTarget.name = row.chestGroupName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let chestsAndStationsAll = [] // configAry赋值
      let chestsByChestGroup = []
      this.getByChestGroupReq.id = row.id
      try {
        chestsAndStationsAll = (await getChestsAndStationsAllAPI()).data
        chestsByChestGroup = (await getChestsAndStationsByChestGroupAPI(this.getByChestGroupReq)).data
      } catch (err) {
        console.log(err)
      }

      chestsAndStationsAll.forEach((chestInChestsAndStationsAll) => {
        let objItem = {}
        objItem.id = chestInChestsAndStationsAll.id
        objItem.display = chestInChestsAndStationsAll.chestNo
        objItem.col = 6
        objItem.checked = false
        objItem.stationId = chestInChestsAndStationsAll.stationId
        objItem.stationName = chestInChestsAndStationsAll.stations.stationName
        for (let i = 0; i < chestsByChestGroup.length; i += 1) {
          if (chestInChestsAndStationsAll.id === chestsByChestGroup[i].chestId) {
            objItem.checked = true
            chestsByChestGroup.splice(i, 1)
            break
          }
        }
        checkItemTemp.push(objItem)
      })
      checkItemTemp.forEach((item) => {
        noSameStation = true
        for (let i = 0; i < this.configAry.length; i += 1) {
          if (item.stationId === this.configAry[i].id) {
            delete item.stationId
            delete item.stationName
            if (this.configAry[i].checkItem) {
              this.configAry[i].checkItem.push(item)
            } else {
              this.configAry[i].checkItem = []
              this.configAry[i].checkItem.push(item)
            }
            noSameStation = false
            break
          }
        }
        if (noSameStation) {
          let obj = {}
          obj.id = item.stationId
          obj.title = item.stationName
          delete item.stationId
          delete item.stationName
          obj.checkItem = []
          obj.checkItem.push(item)
          this.configAry.push(obj)
        }
      })

      this.configDialogVisible = true
    },
    async setUsers(row) {
      this.configAry = [] // configTarget赋值
      this.configTarget.dialogTitle = '分配具备该智能柜组使用权的用户'
      this.configTarget.itemTitle = '请选择用户：'
      this.configTarget.name = row.chestGroupName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let usersAll = [] // configAry赋值
      let usersByChestGroup = []
      this.getByChestGroupReq.id = row.id
      try {
        usersAll = (await getUsersAllAPI()).data
        usersByChestGroup = (await getUsersByChestGroupAPI(this.getByChestGroupReq)).data
      } catch (err) {
        console.log(err)
      }
      let obj = {}
      let i
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      usersAll.forEach((userInUsersAll) => {
        let objItem = {}
        objItem.id = userInUsersAll.id
        objItem.display = userInUsersAll.userName + '(' + userInUsersAll.jobNumber + ')'
        objItem.col = 6
        objItem.checked = false
        for (i = 0; i < usersByChestGroup.length; i += 1) {
          if (userInUsersAll.id === usersByChestGroup[i].userId) {
            objItem.checked = true
            usersByChestGroup.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    closeConfigDialog() {
      this.configDialogVisible = false
    },
    async submitConfig(outObj) {
      let msg
      this.closeConfigDialog()

      if (outObj.title === '分配该智能柜组所拥有的智能柜') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.chestGroupId = outObj.targetId
          tempObj.chestId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeChestsByChestGroupAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配具备该智能柜组使用权的用户') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.chestGroupId = outObj.targetId
          tempObj.userId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeUsersByChestGroupAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.utilMessage.warning('提交配置种类出错')
      }
    },
    // 列表
    async expandTable(row) {
      let usersByChestGroup
      let chestsByChestGroup
      this.getByChestGroupReq.id = row.id
      row.hasUsers = ''
      row.hasChests = ''

      usersByChestGroup = (await getUsersByChestGroupAPI(this.getByChestGroupReq)).data
      chestsByChestGroup = (await getChestsAndStationsByChestGroupAPI(this.getByChestGroupReq)).data

      usersByChestGroup.forEach((item) => {
        if (row.hasUsers === '') {
          row.hasUsers = item.users.userName + '(' + item.users.jobNumber + ')'
        } else {
          row.hasUsers = row.hasUsers + '、' + item.users.userName + '(' + item.users.jobNumber + ')'
        }
      })

      let chestsAryTemp = []
      let noSameStation = true
      chestsByChestGroup.forEach((item) => {
        noSameStation = true
        for (let i = 0; i < chestsAryTemp.length; i += 1) {
          if (item.chests.stationId === chestsAryTemp[i].stationId) {
            if (chestsAryTemp[i].chests === '') {
              chestsAryTemp[i].stationName = item.chests.stations.stationName
              chestsAryTemp[i].chests = item.chests.chestNo
            } else {
              chestsAryTemp[i].chests = chestsAryTemp[i].chests + '、' + item.chests.chestNo
            }
            noSameStation = false
            break
          }
        }
        if (noSameStation) {
          let obj = {}
          obj.stationId = item.chests.stationId
          obj.stationName = item.chests.stations.stationName
          obj.chests = item.chests.chestNo
          chestsAryTemp.push(obj)
        }
      })

      chestsAryTemp.forEach((item) => {
        if (row.hasChests === '') {
          row.hasChests = item.stationName + '(' + item.chests + ')'
        } else {
          row.hasChests = row.hasChests + '、' + item.stationName + '(' + item.chests + ')'
        }
      })

      if (row.hasUsers === '') {
        row.hasUsers = '（无）'
      }
      if (row.hasChests === '') {
        row.hasChests = '（无）'
      }
    },
    getChestGroups() {
      getChestGroupsAPI(this.getReq).then(result => {
        this.total = result.data.count
        let indexTemp = ((this.getReq.currentPage - 1) >= 0 ? (this.getReq.currentPage - 1) : 0) * this.getReq.pageSize
        this.tableAry = result.data.rows.map((item) => {
          this.$set(item, 'hasUsers', '')
          this.$set(item, 'hasChests', '')
          this.$set(item, 'index', indexTemp += 1)
          return item
        })
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.buttonRow{
  margin: 10px;
}
.tableRow{
  margin: 10px;
}
.tableDiv {
  height: 530px;
  overflow-y: scroll;
}
.pageRow{
  margin: 5px;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
.switchDiv {
}
.switch {
  margin: 0px 10px 0px 0px;
}
.switchText {
  display: inline-block;
}
.formTitle {
  text-align: center;
  letter-spacing: 10px;
  font-size: 20px;
}
.formRow {
  padding: 0px 100px 0px 100px;
}
.formButtonDiv {
  text-align: center;
}
.formButton {
  margin: 0px 30px 0px 30px;
}
.el-table th.gutter {
  display: table-cell !important
}
// 滚动条修改
::-webkit-scrollbar {
  width:3px;
}
::-webkit-scrollbar-thumb{
  background: #bcddff;
  border-radius: 5px;
}
</style>
